----------------------------------------------------------------------
-- Bit-serial lesser-than comparison
-- Stephen West, James Carroll
-- BYU ECEn 620, October 2008
----------------------------------------------------------------------
Library ieee;
	use ieee.std_logic_1164.all;
	use ieee.numeric_std.all;
	
entity BitSerialLesser is
	generic(
		word_length:integer:=8;
		code_vector_length:integer:=16;
		system_word_length:integer:=12
	);
	port(
		clk, a_in, b_in, lsb_in:in std_logic;
			lesser_out, a_is_lesser_out, lsb_out: out std_logic
	);
end entity;

architecture BitSerialLesser of BitSerialLesser is
	component Delay is
    	generic(
    		delay:integer:=1
    	);
    	port(
    		clk, input :in std_logic;
    		output: out std_logic
    	);
    end component;
	component BitSerialSub is
		generic(
			word_length:integer:=8;
			code_vector_length:integer:=16
		);
		port(
			clk, a_in, b_in, lsb_in:in std_logic;
				sub_out, lsb_out: out std_logic
		);
	end component;
	signal diff : std_logic:='0';
	signal a_delay, b_delay : std_logic:='0';
	signal a_is_greater,lsb_delay,lsb_delay2:std_logic:='0';
begin
	process(clk, lsb_in)
	begin
		if clk'event and clk='1' then
			lsb_delay2<=lsb_delay;
			if lsb_delay='1' then
				if diff='0' then
					a_is_greater<='1';
				else
					a_is_greater<='0';
				end if;
			end if;
		end if;
	end process;
	
	invert : BitSerialSub port map(clk=>clk, a_in=>a_in, b_in=>b_in, lsb_in=>lsb_in, sub_out=>diff, lsb_out=>open);
	delay1 : Delay
		generic map(delay=>system_word_length)
		port map(clk=>clk, input=> a_in, output=>a_delay);
	delay2 : Delay
		generic map(delay=>system_word_length)
		port map(clk=>clk, input=> b_in, output=>b_delay);
	delay_lsb:Delay 
		generic map(delay=>system_word_length-1)
		port map(clk=>clk, input=>lsb_in, output=>lsb_delay); 
		
	a_is_lesser_out<=not a_is_greater;
	lesser_out<= b_delay when a_is_greater='1' else a_delay;
	lsb_out<=lsb_delay2;
end architecture;
